#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Farmer Li, 公众号: 很酷的程序员/RealCoolEngineer
# @Date: 2021-04-25
# @Question: https://www.zhihu.com/question/456524538

import json
from pathlib import Path

import click

CONTACT_STORE_FILE = './.contacts.json'


class ContactManager:
    def __init__(self, store_file=CONTACT_STORE_FILE) -> None:
        self.contacts = {}
        self.store_file = Path(store_file)
        if self.store_file.exists():
            with self.store_file.open('r') as f:
                self.contacts = json.load(f)

    def save(self):
        with self.store_file.open('w+') as f:
            json.dump(self.contacts, f, indent=2, skipkeys=True)

    def add(self, name, phone):
        if name in self.contacts:
            self.contacts[name]['phone'] = phone
        else:
            self.contacts[name] = {'phone': phone}
        self.save()

    def delete(self, name):
        if name in self.contacts:
            print(f'Deleted contact: {name}')
            self.contacts.pop(name)
            self.save()
        else:
            print(f'Name not exists: {name}')

    def get(self, name):
        if name in self.contacts:
            print(f'Found contact: {name}: {self.contacts[name]["phone"]}')
            return self.contacts[name]
        else:
            print(f'Contact not exists: {name}')


@click.command()
@click.option('--add', is_flag=True, help='Add or update contact')
@click.option('--get', is_flag=True, help='Get contact')
@click.option('--delete', is_flag=True, help='Delete contact')
@click.option('--name', help='Delete contact')
@click.option('--phone', help='Delete contact')
def main(add, get, delete, name, phone):
    contacts = ContactManager()

    if add:
        if name and phone:
            contacts.add(name, phone)
        else:
            print('Must use "--name" and "--phone" to set contact info')
    else:
        if name:
            if get:
                contacts.get(name)
            elif delete:
                contacts.delete(name)
        else:
            print('Must use "--name" set contact name')


if __name__ == '__main__':
    main()
